package com.arong.biBackend.manager;

import com.arong.biBackend.exception.BusinessException;
import org.redisson.api.RRateLimiter;
import org.redisson.api.RateIntervalUnit;
import org.redisson.api.RateType;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import static com.arong.biBackend.common.ErrorCode.TOO_MANY_REQUEST;

@Service
public class RedisLimiterManager {

    @Resource
    private RedissonClient redissonClient;

    public void doRateLimit(String key) {
        // 创建一个名字为 user_limiter的限流器
        RRateLimiter rateLimiter = redissonClient.getRateLimiter(key);
        // 每秒两个请求，连续的请求下，最多只能由1个请求被允许通过
        rateLimiter.trySetRate(RateType.OVERALL,2,1, RateIntervalUnit.SECONDS);
        // 一个操作请求一个令牌
        boolean capOn = rateLimiter.tryAcquire(1);

        if(!capOn) {
            throw new BusinessException(TOO_MANY_REQUEST);
        }
    }
}
